/**
 * Session API 客户端
 *
 * 提供与后端 Session API 交互的方法
 */

const API_BASE_URL = 'http://localhost:3000/api';

// ============================================================================
// 类型定义
// ============================================================================

export interface ApiResponse<T = any> {
  success: boolean;
  data?: T;
  error?: {
    code: string;
    message: string;
    details?: any;
  };
  timestamp: string;
}

export interface Session {
  id: string;
  createdAt: string;
  updatedAt: string;
  agentOptions: Record<string, any>;
  messages: Message[];
  metadata?: Record<string, any>;
  title?: string;
  subAgentId?: string;
  archived?: boolean;
}

export interface Message {
  id: string;
  role: 'user' | 'assistant' | 'system';
  content: string;
  timestamp: string;
  metadata?: Record<string, any>;
  subAgentId?: string;
}

export interface CreateSessionRequest {
  agentOptions?: Record<string, any>;
  metadata?: Record<string, any>;
  title?: string;
  subAgentId?: string;
}

export interface AddMessageRequest {
  role: 'user' | 'assistant' | 'system';
  content: string;
  metadata?: Record<string, any>;
  subAgentId?: string;
}

export interface ListSessionsOptions {
  limit?: number;
  offset?: number;
  sortBy?: 'createdAt' | 'updatedAt';
  sortOrder?: 'asc' | 'desc';
  search?: string;
}

export interface ListSessionsResult {
  sessions: Session[];
  total: number;
  limit: number;
  offset: number;
}

export interface SessionStats {
  totalSessions: number;
  totalMessages: number;
  archivedSessions: number;
  activeSessions: number;
}

// ============================================================================
// Session API 客户端
// ============================================================================

/**
 * 创建新的 session
 */
export async function createSession(
  request: CreateSessionRequest = {}
): Promise<Session> {
  const response = await fetch(`${API_BASE_URL}/session/create`, {
    method: 'POST',
    headers: {
      'Content-Type': 'application/json',
    },
    body: JSON.stringify(request),
  });

  if (!response.ok) {
    throw new Error(`Failed to create session: ${response.statusText}`);
  }

  const data: ApiResponse<Session> = await response.json();

  if (!data.success || !data.data) {
    throw new Error(data.error?.message || 'Failed to create session');
  }

  return data.data;
}

/**
 * 获取 session 详情
 */
export async function getSession(sessionId: string): Promise<Session> {
  const response = await fetch(`${API_BASE_URL}/session/${sessionId}`);

  if (!response.ok) {
    throw new Error(`Failed to get session: ${response.statusText}`);
  }

  const data: ApiResponse<Session> = await response.json();

  if (!data.success || !data.data) {
    throw new Error(data.error?.message || 'Failed to get session');
  }

  return data.data;
}

/**
 * 删除 session
 */
export async function deleteSession(sessionId: string): Promise<boolean> {
  const response = await fetch(`${API_BASE_URL}/session/${sessionId}`, {
    method: 'DELETE',
  });

  if (!response.ok) {
    throw new Error(`Failed to delete session: ${response.statusText}`);
  }

  const data: ApiResponse = await response.json();

  return data.success;
}

/**
 * 列出所有 sessions
 */
export async function listSessions(
  options: ListSessionsOptions = {}
): Promise<ListSessionsResult> {
  const params = new URLSearchParams();

  if (options.limit !== undefined) params.set('limit', options.limit.toString());
  if (options.offset !== undefined) params.set('offset', options.offset.toString());
  if (options.sortBy) params.set('sortBy', options.sortBy);
  if (options.sortOrder) params.set('sortOrder', options.sortOrder);
  if (options.search) params.set('search', options.search);

  const url = `${API_BASE_URL}/session?${params.toString()}`;
  const response = await fetch(url);

  if (!response.ok) {
    throw new Error(`Failed to list sessions: ${response.statusText}`);
  }

  const data: ApiResponse<ListSessionsResult> = await response.json();

  if (!data.success || !data.data) {
    throw new Error(data.error?.message || 'Failed to list sessions');
  }

  return data.data;
}

/**
 * 获取 session 统计信息
 */
export async function getSessionStats(): Promise<SessionStats> {
  const response = await fetch(`${API_BASE_URL}/session/stats`);

  if (!response.ok) {
    throw new Error(`Failed to get session stats: ${response.statusText}`);
  }

  const data: ApiResponse<SessionStats> = await response.json();

  if (!data.success || !data.data) {
    throw new Error(data.error?.message || 'Failed to get session stats');
  }

  return data.data;
}

/**
 * 向 session 添加消息
 */
export async function addMessage(
  sessionId: string,
  request: AddMessageRequest
): Promise<Message> {
  const response = await fetch(`${API_BASE_URL}/session/${sessionId}/message`, {
    method: 'POST',
    headers: {
      'Content-Type': 'application/json',
    },
    body: JSON.stringify(request),
  });

  if (!response.ok) {
    throw new Error(`Failed to add message: ${response.statusText}`);
  }

  const data: ApiResponse<Message> = await response.json();

  if (!data.success || !data.data) {
    throw new Error(data.error?.message || 'Failed to add message');
  }

  return data.data;
}

/**
 * 归档 session
 */
export async function archiveSession(sessionId: string): Promise<boolean> {
  const response = await fetch(`${API_BASE_URL}/session/${sessionId}/archive`, {
    method: 'POST',
  });

  if (!response.ok) {
    throw new Error(`Failed to archive session: ${response.statusText}`);
  }

  const data: ApiResponse = await response.json();

  return data.success;
}

